﻿/******************************************************************************
* Author: 671643387@qq.com
* @MR.Luo
*****************************************************************************/

#include <boost/bind.hpp>
#include "Common.h"
#include "EchoConnectionFactory.h"
using namespace dev::net;

EchoConnectionFactory::EchoConnectionFactory()
#if defined(__LINUX__)
: bufPool_(CONN_SS_SIZE)
, connPool_(sizeof(dev::net::TcpConnection))
#endif
{
}


EchoConnectionFactory::~EchoConnectionFactory()
{
}

TcpConnectionPtr EchoConnectionFactory::createConnection(dev::net::sock_t sock, size_t isBufSize, size_t osBufSize)
{
#if defined(__WINDOWS__)
    return TcpConnectionPtr(new TcpConnection(sock, isBufSize, osBufSize),
        boost::bind(&EchoConnectionFactory::destroyConnection, this, _1));
#elif defined(__LINUX__)
    boost::shared_array<char> isBuff((char*)bufPool_.malloc(),
        boost::bind(&EchoConnectionFactory::freeBuff, this, _1));
    boost::shared_array<char> osBuff((char*)bufPool_.malloc(),
        boost::bind(&EchoConnectionFactory::freeBuff, this, _1));
    void* conn = connPool_.malloc();
    if (conn)
    {
        return TcpConnectionPtr(new(conn) TcpConnection(sock, isBuff, osBuff, isBufSize, osBufSize),
            boost::bind(&EchoConnectionFactory::destroyConnection, this, _1));
    }
    return TcpConnectionPtr();
#endif 
}

#if defined(__LINUX__)
void EchoConnectionFactory::freeBuff(void* mem)
{
    bufPool_.free(mem);
}
#endif

void EchoConnectionFactory::destroyConnection(dev::net::TcpConnection* conn)
{
    assert(conn);
#if defined(__WINDOWS__)
    delete conn;
#elif defined(__LINUX__)
    connPool_.free(conn);
#endif
}
